<!--排污许可证管理-自行检测方案-->
<template>
    <Layout>
        <Form ref="form1" :model="dataToQuery" :label-width="120">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="8" v-if="!modelTcheme">
                    <FormItem label="单位名称：" prop="order">
                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName'
                                      :orgTree="true"
                                      :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="方案名称：">
                        <Input class='query-form-el' type='text' v-model='dataToQuery.name'></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <!--<Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form" v-if="!modelTcheme">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <Button type="primary" class="ivu-btn-add" icon="md-cloud-download"
                            :loading="buttonLoading" @click="batchDownload">批量下载</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
               :loading='pageStatus.loading'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="this.getModalTitle('自行监测方案')" :transfer=false :mask-closable="false" v-model="dialogShow"
               v-if="dataToView && dialogShow" :width=800 class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                          :model="dataToView" :rules="mode === 'view'?{}:ruleCustom"
                          :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='所属二级集团：' prop='belongOrgId'>
                                    <div v-if="mode === 'view'">{{ dataToView.belongOrgName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写所属二级集团" type='text' v-model='dataToView.belongOrgId'></Input>-->
                                    <Select v-else class='query-form-el' placeholder="集团名称"
                                            v-model='dataToView.belongOrgId' label-in-value @on-change="belongChange">
                                        <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">
                                            {{item.orgName}}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='单位名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写单位名称" type='text' v-model='dataToView.companyId'></Input>-->
                                    <div v-else>
                                        <cascader-dom v-if="show" class='query-form-el' ref='orgCascader'
                                                      @setOrgInfo='setCompanyId' @setOrgname="setCompanyName"
                                                      :orgTree="true"
                                                      :currentOrgId="dataToView.companyId"
                                                      :rootOrgId="dataToView.belongOrgId"
                                                      :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='方案名称：' prop='name'>
                                    <div v-if="mode === 'view'">{{ dataToView.name }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写方案名称" type='text'
                                           v-model='dataToView.name'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='监测频次：' prop='monitorFrequency'>
                                    <div v-if="mode === 'view'">{{ dataToView.monitorFrequencyName }}</div>
                                    <Select v-else v-model='dataToView.monitorFrequency' clearable>
                                        <Option v-for="item in dictMap['env-00031']" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around"
                             class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="方案附件：">
                                    <div v-show="dataToView.idFiles.length>0"
                                         v-for="(item,index) in dataToView.idFiles">
                                        <a @click="downloadFiles(item,index)"><span
                                                style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                        <Progress v-show="uploadListVisible[index]"
                                                  :percent="uploadListPercent[index]"></Progress>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="方案附件：" prop="idFiles">
                                    <div>
                                        <Upload ref="upload"
                                                :before-upload="(file) => { beforeUpload1(file, 'id', 'selfTestTcheme') }"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 10px">
                                                <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                                <!--<span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>-->
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles"
                                         :key='item'>
                                        <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash"
                                                @click="removeFile1(item.id, 'id', 'selfTestTcheme')"
                                                style="margin-left: 5px;margin-bottom: 3px"/>
                                        <Progress v-show="uploadListVisible[index]"
                                                  :percent="uploadListPercent[index]"></Progress>
                                        <!--<Progress  v-show="filePercentVisible[index]" :percent="filePercent[index]"></Progress>-->
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='上传人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写上传人" type='text' readonly
                                           v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='上传时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择上传时间" readonly
                                                v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='上传人手机号：' prop='registrantPhone'>
                                    <div v-if="mode === 'view'">{{ dataToView.registrantPhone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写上传人手机号" type='text'
                                           v-model='dataToView.registrantPhone'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>

                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定
                </Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

       <div v-show="downloading"
           style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:99999;background-color:#000000;opacity:0.5;">
           <svg-bar style="position:absolute;top:50%;left:50%;margin-left:-100px;margin-top:-100px" 
              :options="options" :value="batchProcess"></svg-bar>
       </div>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {formatDate} from '@/tools/index'
    import svgBar from 'svg-progress-bar'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';

    export default {
        components: {
            cascaderDom,svgBar
        },
        props: ['companyId', 'modelTcheme'],
        data() {
            return {
                ...this.createCommonDataField(),
                imgUrl: "",
                columns1: [
                    {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    {key: 'belongOrgName', title: '所属二级集团', align: 'center', minWidth: 120,},
                    {key: 'companyName', title: '单位名称', align: 'center', minWidth: 120,},
                    {key: 'name', title: '方案名称', align: 'center', minWidth: 120,},
                    {key: 'monitorFrequencyName', title: '监测频次', align: 'center', minWidth: 120,},
                    {key: 'createUserName', title: '方案上传人', align: 'center', minWidth: 120,},
                    {key: 'createDate', title: '方案上传时间', align: 'center', minWidth: 120, render: this.renderCellDate},
                    {key: 'ifReport', title: '监测报告是否上传', align: 'center', minWidth: 120,
                        render: (h, params) => {return h('span',{style: {fontSize: '12px', color: params.row.ifReport === '1'?'red':''}},
                            params.row.ifReport==='1'?'已上传':'未上传')}},
                    // { key:'registrantPhone',title: '上传人手机号',  align: 'center',minWidth: 120, },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: this.modelTcheme?80:160,
                        align: 'center',
                        render: (h, params) => {
                            if (this.modelTcheme) {
                                return h('div', [
                                    h('A', {
                                        props: { type: 'primary', size: 'small' },
                                        style: { fontSize: '12px' },
                                        on: {
                                            click: () => {
                                                this.checkSave(params.row);
                                            }
                                        }
                                    }, '选择'),
                                ]);
                            } else {
                                if (params.row.ifReport==='0'&&(this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId  || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                    ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined)) {
                                    return h('div', [
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            style: {fontSize: '14px',},
                                            on: {
                                                click: () => {
                                                    this.viewData(params);
                                                }
                                            }
                                        }, '详情'),
                                        h('Divider', {props: {type: 'vertical'}}, ''),
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            disabled: true,
                                            style: {fontSize: '14px'},
                                            on: {
                                                click: () => {
                                                    this.editData(params);
                                                }
                                            }
                                        }, '修改'),
                                        h('Divider', {props: {type: 'vertical'}}, ''),
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            style: {fontSize: '14px', color: 'red'},
                                            on: {
                                                click: () => {
                                                    this.deleteData(params);
                                                }
                                            }
                                        }, '删除')
                                    ]);
                                } else {
                                    return h('div', [
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            style: {fontSize: '14px',},
                                            on: {
                                                click: () => {
                                                    this.viewData(params);
                                                }
                                            }
                                        }, '详情'),
                                        h('Divider', {props: {type: 'vertical'}}, ''),
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            style: {fontSize: '14px', color: '#c5c8ce'}
                                        }, '修改'),
                                        h('Divider', {props: {type: 'vertical'}}, ''),
                                        h('A', {
                                            props: {type: 'primary', size: 'small'},
                                            style: {fontSize: '14px', color: '#c5c8ce'}
                                        }, '删除')
                                    ]);
                                }
                            }
                        }
                    },
                ],
                ruleCustom: {
                    belongOrgId: [{required: true, message: '请填写所属二级集团', trigger: 'change',}],
                    companyId: [{required: true, message: '请填写单位名称', trigger: 'change',}],
                    name: [{required: true, message: '请填写方案名称', trigger: 'change',}],
                    createUserName: [{required: true, message: '请填写上传人', trigger: 'change',}],
                    createDate: [{required: true, message: '请填写上传时间', trigger: 'change', type: 'date'}],
                    registrantPhone: [{
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(this.dataToView.registrantPhone))) {
                                callback(' ');
                                // this.$Message.error("请填写有效的的手机号")
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    idFiles: [{
                        validator: (rule, value, callback) => {
                            if (this.dataToView.idFiles.length < 1) {
                                callback('附件必须上传')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }]
                },
                tableHeight: 10,
                dictMap: {},
                punishment: false,
                penaltyAmount: true,
                // api
                queryUrl: Api.queryEnTable.replace('{{table}}', 'SelfTestTcheme'),
                exportUrl: Api.exportEnTable.replace('{{table}}', 'SelfTestTcheme'),
                deleteUrl: Api.deleteEnTable.replace('{{table}}', 'SelfTestTcheme'),
                getUrl: Api.getEnTable.replace('{{table}}', 'SelfTestTcheme'),
                updateUrl: Api.updateEnTable.replace('{{table}}', 'SelfTestTcheme'),
                saveUrl: Api.saveEnTable.replace('{{table}}', 'SelfTestTcheme'),

                currentUser: JSON.parse(sessionStorage('userId').get('userId')),
                show: true,
                buttonLoading: false,
                batchProcess:0,
                downloading:false,
            }
        },
        computed: {
            options: function() {
            	return {
            		radius: 50,//大小
            		duration: 2,//变化时间长度
            		circleWidth: 5,//圆环宽度
            		pathColors: ['#A2A2A2', '#FA5657'], //圆环 底色和 上面的颜色
            		circleLineCap: 'round',//进度条 形状  圆环 或者矩形
            		text: function (value) {
                            return this.htmlifyNumber(value) + '<span style="font-size: 0.4em;">%</span>';
                            },
                    textColor: 'rgb(33, 150, 243)'
            	}
            }
        },
        async mounted() {
            this.setTableHeight();
            await this.$http.get(Api.queryDictBycode+"env-00031",{}).then((res)=>{
                // 数据字典 list 转 map，方便调用
                this.dictMap = {
                    'env-00031':this.dictListToMap(res.data.data['env-00031']),
                }
            })
            this.query();
            this.selectSecGroupNames()
            this.$Loading.config({
                color: '#5cb85c',
                failedColor: 'red',
                height: 5
            });
        },
        methods: {
            ...pageCommonFunction,
            batchDownload(){
                var _this = this;
                _this.downloading = true
                var url = Api.mongoBatchDownload;
                var ids = [];
                var fileNames = [];
                _this.dataTable.forEach(item=>{
                    ids.push(item.id)
                    fileNames.push(item.companyName+'-'+item.name)
                })
				_this.batchProcess = 0;
                let formData = new FormData();
                formData.append("ids", ids); // 文件对象
                formData.append("fileNames", fileNames); // 文件对象
                _this.$http.post(url, formData, {
                    responseType: 'blob',      //告诉服务器我们需要的响应格式
                   downloadProgress:function(e){
                       _this.batchProcess = 100 * (e.loaded / e.total);
                       if(_this.batchProcess == 100){
                           _this.downloading = false;
                       }
                   }
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: 'application/zip'     //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = _this.formatDate(new Date(), 'yyyyMMddhhmmss') + ".zip";
                    aLink.click()
                    document.body.appendChild(aLink)
                }, function(res){
                    _this.$Loading.error();
                })
            },
            checkSave(row){
                this.$emit('getSelectModelData',row);
            },
            selectSecGroupNames() {
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel = res.data.data
                }).catch(e => {
                })
            },
            belongChange(value) {
                this.$set(this.dataToView, 'belongOrgId', value.value)
                this.$set(this.dataToView, 'belongOrgName', value.label)
                this.dataToView.companyId = null
                this.dataToView.companyName = null
                this.$refs.orgCascader.resetCurrentOrg();
                this.show = false;
                setTimeout(() => {
                    this.show = true
                }, 0)
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                if (this.companyId) {
                    this.dataToQuery.companyId = this.companyId
                    // this.dataToQuery.ifReport = '0'
                }
                // if(this.dataToQuery.eventTypeIdsArrays) {
                //     this.dataToQuery.eventTypeIds = this.arrayToInFormat(this.dataToQuery.eventTypeIdsArrays)
                // }
                // this.dataToQuery.orgId = this.currentUser.companyId;
                this.queryAjax();
            },

            submit(name) {
                this.submitAjax(name);
            },
            createEmptyDataToAdd() {
                return {
                    createDate: new Date(),
                    createUserId: this.currentUser.userId,
                    createUserName: this.currentUser.userName,
                    productionNum: null,
                    storageNum: null,
                    disposalNum: null,
                    id: this.get_uuid(),
                    idFiles: [],
                }
            },
            async afterDataToViewInit() {
                await this.getFiles1('id', 'selfTestTcheme');
            },
            formatDate(date, fmt) {
                if (typeof date == 'string') {
                    return date;
                }
                if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
                if (!date || date == null) return null;
                let o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    'S': date.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
                return fmt
            },
        },
        watch: {},
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>